package com.eagle.common.util;

import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

import java.util.Iterator;
import java.util.Map;

/**
 * 文件名称: MapperUtil.java<br>
 * 类描述:这个是工具类，主要是为jackson,xml解析提供的公用方法.<br>
 **/
public class MapperUtil {
    /**需要过滤的序列化类，类上面要注解@JsonFilter
     *@param  mapper
     *         当前mapper
     *@param   filterMap
     *          需要过滤的类名与相应字段的映射
     * **/
    public static  void  setSerializationFilter(ObjectMapper mapper, Map< Class<?>, String[] >...filterMap){
        if ( filterMap != null ){
            for(Map<Class<?>, String[] > map :filterMap){
                //批量解析并设置
                for(Iterator<Class<?>> it = map.keySet().iterator(); it.hasNext();){
                    Class<?> classCast = it.next();
                    String[] value = (String[]) map.get(classCast);
                    //得到当前类JsonFilter
                    JsonFilter jsonFilter = classCast.getAnnotation(JsonFilter.class);
                    if ( jsonFilter != null ){
                        FilterProvider filter = new SimpleFilterProvider().addFilter(jsonFilter.value(), SimpleBeanPropertyFilter.serializeAllExcept(value));
                        mapper.setFilters(filter);
                    }
                }
            }
        }
    }
}
